import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    location: null,
    cartData: null,
    addressLocation: null,
    address: null,
    addressEdit: null
  },
  getters: {
    location: state => {
      if (state.location) {
        return state.location;
      }
      const locationText = window.localStorage.getItem('Location');
      if (locationText) {
        return JSON.parse(locationText);
      }
      return null;
    },
    addressEdit: state => {
      if (state.addressEdit) {
        return state.addressEdit;
      }
      const addressText = window.sessionStorage.getItem('addressEdit');
      if (addressText) {
        return JSON.parse(addressText);
      }
      return null;
    },
    addressLocation: state => state.addressLocation,
    address: state => {
      if (state.address) {
        return state.address;
      }
      const addressText = window.sessionStorage.getItem('address');
      if (addressText) {
        return JSON.parse(addressText);
      }
      return null;
    },
    cartData: state => {
      if (state.cartData) {
        return state.cartData;
      }
      const cartDataText = window.localStorage.getItem('cartData');
      if (cartDataText) {
        return JSON.parse(cartDataText);
      }
      return null;
    }
  },
  mutations: {
    SET_LOCATION: (state, location) => {
      state.location = location;
      window.localStorage.setItem('Location', JSON.stringify(location));
    },
    SET_CARTDATA: (state, cartData) => {
      state.cartData = cartData;
      if (cartData) {
        window.localStorage.setItem('cartData', JSON.stringify(cartData));
      } else {
        window.localStorage.removeItem('cartData');
      }
    },
    SET_ADDRESS: (state, address) => {
      state.address = address;
      window.sessionStorage.setItem('address', JSON.stringify(address))
    },
    SET_ADDRESS_LOCATION: (state, location) => {
      state.addressLocation = location;
    },
    SET_ADDRESS_EDIT: (state, address) => {
      window.sessionStorage.setItem('addressEdit', JSON.stringify(address));
      state.addressEdit = address;
    },
  },
  actions: {

  }
})
